package com.huxiaohui.ssbx.service.impl;

import cn.hutool.core.util.IdUtil;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.huxiaohui.ssbx.service.ISessionService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class SessionServiceImpl implements ISessionService {
    // 会话超时时间（分钟）
    private static final int SESSION_TIMEOUT_MINUTES = 180;
    // 存储会话信息
    private final Cache<String, SessionInfo> sessions = Caffeine.newBuilder()
        .expireAfterWrite(SESSION_TIMEOUT_MINUTES, TimeUnit.MINUTES)
        .build();
//    private final Map<String, SessionInfo> sessions = new ConcurrentHashMap<>();
    

    
    @Override
    public String getSessionId() {
        String sessionId = IdUtil.fastUUID();
        SessionInfo sessionInfo = new SessionInfo(sessionId, LocalDateTime.now());
        sessions.put(sessionId, sessionInfo);
        return sessionId;
    }
    
    /**
     * 验证会话是否有效
     */
    public boolean isValidSession(String sessionId) {
        SessionInfo sessionInfo = sessions.getIfPresent(sessionId);
        if (sessionInfo == null) {
            return false;
        }
        
        LocalDateTime now = LocalDateTime.now();
        // 更新最后访问时间
        sessionInfo.setLastAccessTime(now);
        return true;
    }
    
    /**
     * 清理过期会话
     */
    public void cleanupExpiredSessions() {
        LocalDateTime now = LocalDateTime.now();
        sessions.asMap().values().removeIf(sessionInfo -> sessionInfo.getLastAccessTime()
            .plusMinutes(SESSION_TIMEOUT_MINUTES)
            .isBefore(now));
    }
    
    /**
     * 获取会话信息
     */
    public SessionInfo getSessionInfo(String sessionId) {
        return sessions.getIfPresent(sessionId);
    }
    
    /**
     * 会话信息类
     */
    @Data
    public static class SessionInfo {
        private final String sessionId;
        private final LocalDateTime createdTime;
        private LocalDateTime lastAccessTime;
        
        public SessionInfo(String sessionId, LocalDateTime createdTime) {
            this.sessionId = sessionId;
            this.createdTime = createdTime;
            this.lastAccessTime = createdTime;
        }
        

    }
}
